package com.isyscore.os.metadata.service.impl;

import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.isyscore.os.core.util.InitiallyUtils;
import com.isyscore.os.metadata.dao.TableAliasMapper;
import com.isyscore.os.metadata.model.entity.TableAlias;
import com.isyscore.os.metadata.service.TableAliasService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

import java.util.HashMap;
import java.util.Map;

@Slf4j
@Service
public class TableAliasServiceImpl extends ServiceImpl<TableAliasMapper, TableAlias> implements TableAliasService {
    private static  Map<String,String> aliasMap ;

    @Override
    public  Map getAllAliasCache(){
        if(aliasMap==null){
            aliasMap = new HashMap<>();
            for (TableAlias tableAlias :InitiallyUtils.markIgnore(()->list())) {
                aliasMap.put(tableAlias.getSourceId()+tableAlias.getDatabaseName()+tableAlias.getTableName(),tableAlias.getAlias());
            }
        }
        return aliasMap;
    }


    @Override
    public void setTableAlias(Long dataSourceId, String databaseName, String tableName, String alias) {
        TableAlias tableAlias = new TableAlias();
        tableAlias.setSourceId(dataSourceId);
        tableAlias.setDatabaseName(databaseName);
        tableAlias.setTableName(tableName);
        if(aliasMap==null){
            getAllAliasCache();
        }
        aliasMap.put(dataSourceId+databaseName+tableName,alias);

        if(InitiallyUtils.markIgnore(()->getOne(Wrappers.query(tableAlias)))!=null){
            UpdateWrapper<TableAlias> updateWrapper = new UpdateWrapper<TableAlias>();
            updateWrapper.lambda().eq(TableAlias::getSourceId,dataSourceId).eq(TableAlias::getDatabaseName,databaseName).eq(TableAlias::getTableName,tableName).set(TableAlias::getAlias,alias);
            InitiallyUtils.markIgnore(()->update(updateWrapper));
        }else{
            tableAlias.setAlias(alias);
            InitiallyUtils.markIgnore(()->save(tableAlias));
        }
    }


}
